#!/usr/bin/env python
# coding: utf-8
from pywinauto import Application
import keyboard
from psutil import process_iter
import grpc

from rpc import service_pb2, service_pb2_grpc
from concurrent import futures
import json

class WechatService(service_pb2_grpc.WechatService):
     def sendMessage(self, request, context):
          destination = request.destination
          content = request.content
          print("destination:", destination, ",content:", content)
          sendMessage(wx_win, destination, content)
          response = service_pb2.SendMessageResp()
          response.ret = 0
          return response
     def fetchMessageList(self, request, context):
          destination = request.destination
          msg_list = get_message_list(wx_win, destination)
          response = service_pb2.FetchMessageListResp()
          response.ret = 0
          response.message = json.dumps(msg_list)
          return response
     
def serve():
     server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
     service_pb2_grpc.add_WechatServiceServicer_to_server(WechatService(), server)
     server.add_insecure_port("[::]:" + '1369')
     server.start()
     print("Server started, listening on " + '1369')
     server.wait_for_termination()


def find_wechat():
    PIDS = process_iter()
    for pid in PIDS:
        pid_dic = pid.as_dict(attrs=['pid', 'name'])
        if pid_dic['name'] == 'WeChat.exe':
            return pid_dic['pid']
    return None
    
def get_message_list(win, target):
    #wx_chat_win = wx_win.child_window(title=target, control_type='ListItem')
    #wx_chat_win.click_input()

    msg_dlg = win.child_window(title='消息', control_type='List')
    msg_item_iter = msg_dlg.children(control_type='ListItem')
    message_list = []
    for msg_item in msg_item_iter:
        if not msg_item.children():
            continue
        sender = ''.join(msg_item.children()[0].children_texts())
        content = msg_item.element_info.name
        message_list.append({'sender': sender, 'msg': content})
    return message_list

def sendMessage(win, target, content):
    wx_chat_win = wx_win.child_window(title=target, control_type='ListItem')
    wx_chat_win.click_input()

    wx_chat_edit = wx_win.child_window(title=target, control_type='Edit')
    wx_chat_edit.click_input()

    wx_chat_button = wx_win.child_window(title='发送(S)', control_type='Button')

    keyboard.write(content)
    keyboard.send('enter')

process_id = find_wechat()

app = Application('uia').connect(process=process_id)

wx_win = app.window(class_name='WeChatMainWndForPC')

chat_history = set()
     

if __name__ == "__main__":
     serve()